package com.ay.smartpark.sdk.common.utils;


import com.ay.smartpark.sdk.common.base.OnlineUserInfo;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ServiceUtils implements InitializingBean, ApplicationContextAware {

    private static ApplicationContext applicationContext;

    private static Map<String, Map<String, Object>> serviceMap = new HashMap<>();

    @Override
    public void afterPropertiesSet() throws Exception {

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ServiceUtils.applicationContext = applicationContext;
    }

    public static <T> T getServiceImpl(String serviceName, Class clazz) {
        Map<String, Object> services = serviceMap.get(clazz.getName());
        if (CheckUtils.mapIsEmpty(services)) {
            services = applicationContext.getBeansOfType(clazz);
            serviceMap.put(clazz.getName(), services);
        }
        OnlineUserInfo onlineUserInfo = OnlineUserInfoUtil.getOnlineUserInfo();
        String packageName = Class.class.getPackage().getName();
        if (onlineUserInfo != null) {
            String entId = "";
            if(packageName.equals("components")){
                entId = onlineUserInfo.getEntId();
            }
            String serviceImplName = entId + serviceName;
            return (T) services.get(serviceImplName);
        } else {
            return null;
        }
    }

    public static <T> T getService(Class clazz) {
        Map<String, Object> services = serviceMap.get(clazz.getName());
        if (CheckUtils.mapIsEmpty(services)) {
            services = applicationContext.getBeansOfType(clazz);
            serviceMap.put(clazz.getName(), services);
        }
        String serviceName = StringUtils.toLowerCaseFirstOne(clazz.getSimpleName());
        return (T) services.get(serviceName);
    }
}
